<?php

namespace app\common\cachemodel\zlcr3;

use app\common\cachemodel\ZlcrAstr;
use app\common\model\BaseCache;
use app\common\model\User;
use XznsTools\cache\CacheManage;

class Zlcr3ConsultChatRecordAstr extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.zlcr3_consult_chat_record_astr';

    protected $cacheModel = 'voice_consult.astr_chat_id';

    /**
     * 获取 咨询消息列表
     * @param int $astrId 咨询师ID
     * @param int $type 1=>待转化  2=>沟通中  3=>我的客户
     * @param int $page
     * @param int $limit
     * @return array
     * @throws \Exception
     */
    public function pageDataIds(int $astrId, int $type, int $page, int $limit)
    {
        $resData = CacheManage::getInstance()
            ->setCacheConfig($this->cacheModel, $astrId)
            ->setPage($page)
            ->setListKeyType($type)
            ->setPageSize($limit)
            ->setSort('desc')
            ->getListPageDataIds(function ($isCache = true, $sortType = 'desc') use ($astrId, $type)
            {
                try
                {
                    $where = ['astr_id' => $astrId];
                    switch ($type)
                    {
                        case 2: //  沟通中
                            $where['reply_num'] = ['>', 0];
                            $where['consult_num'] = 0;
                            break;
                        case 3: //  我的客户
                            $where['consult_num'] = ['>', 0];
                            break;
                        default:    // 默认为 1
                            $where['reply_num'] = 0;
                            $where['consult_num'] = 0;
                    }

                    $data = $this->where($where)->order("last_chat_detail_time {$sortType}")->column('last_chat_detail_time', 'id');

                    $resData = [];
                    foreach ($data as $id => $lastTime)
                    {
                        $resData[$id] = ['last_chat_detail_time' => $lastTime];
                    }

                    return $resData;
                }
                catch (\Exception $e)
                {
                    return [];
                }
            }, 'last_chat_detail_time', 0);

        if ($resData['data'])
        {
            $resData['data'] = array_map('intval', array_keys($resData['data']));
        }
        return $resData;
    }

    /**
     * 初始化 咨询会话ID
     * @param array $data
     * @return int
     */
    public function SaveData(array $data): int
    {
        try
        {
            $id = $this->insertGetId($data);

            $this->listDataAdd($data['astr_id'], [$id => $data['last_chat_detail_time']], 1);   //
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('astrid_uid', $data['astr_id'] . ':' . $data['uid'])->rmCache('astrid_uid');
            return (int)$id;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return 0;
        }
    }

    public function updateData(int $id, int $astrId, array $data, int $listType = 1, int $rmListType = -1)
    {
        try
        {
            $data['update_time'] = time();
            $this->where(['id' => $id])->update($data);

            if (isset($data['last_chat_detail_time']))
            {
                $this->listDataAdd($astrId, [$id => $data['last_chat_detail_time']], $listType);
            }
            if ($rmListType > 0)
            {
                $this->listDataDel($astrId, [$id], $rmListType);
                $this->setAstrUnreadAllNumInc($astrId, $id, $rmListType, 2, 0);
            }
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $id)->rmCache();
            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 用户端 更新信息
     * @param $uid
     * @param $astrId
     * @param $data
     * @return bool
     */
    public function userSendUpdate($uid, $astrId, $data)
    {
        try
        {
            $chatId = $this->getIdByAstrIdAndUid($astrId, $uid);
            $info = $chatId > 0 ? $this->getInfoById($chatId) : null;
            if ($info)
            {
                if ($info['consult_num'] > 0)
                {   // 我的 客户
                    $listType = 3;
                } elseif ($info['reply_num'] > 0)
                {   // 沟通中
                    $listType = 2;
                } else
                {   // 待转化
                    $listType = 1;
                }

                if (isset($data['unread_num']))
                {
                    if ($info['consult_num'] > 0)
                    {
                        $msgType = 3;
                    } elseif ($info['reply_num'] > 0)
                    {
                        $msgType = 2;
                    } else
                    {
                        $msgType = 1;
                    }
                    // 消息已读
                    $this->setAstrUnreadAllNumInc($astrId, $chatId, $msgType, 1, 1);
                }

                $this->updateData($info['id'], $astrId, $data, $listType);
            } else
            {   // 初始化
                $insertData = [
                    'uid' => $uid,
                    'status' => 1,
                    'astr_id' => $astrId,
                    'create_time' => time(),
                ];

                if (isset($data['last_chat_detail_id']))
                {
                    $insertData['last_chat_detail_id'] = $data['last_chat_detail_id'];
                }
                if (isset($data['last_chat_detail_time']))
                {
                    $insertData['last_chat_detail_time'] = $data['last_chat_detail_time'];
                }
                if (isset($data['user_last_msg_time']))
                {
                    $insertData['user_last_msg_time'] = $data['user_last_msg_time'];
                }
                if (isset($data['unread_num']))
                {
                    $insertData['unread_num'] = 1;
                }
                if (isset($data['question_num']))
                {
                    $insertData['question_num'] = 1;
                }
                if (isset($data['delay_num']))
                {
                    $insertData['delay_num'] = 1;
                }
                if (isset($data['call_num']))
                {
                    $insertData['call_num'] = 1;
                }

                $insertChatId = $this->SaveData($insertData);

                if (isset($data['unread_num']))
                {
                    if (isset($data['consult_num']))
                    {
                        $msgType = 3;
                    } elseif (isset($data['reply_num']))
                    {
                        $msgType = 2;
                    } else
                    {
                        $msgType = 1;
                    }
                    // 消息已读
                    $this->setAstrUnreadAllNumInc($astrId, $insertChatId, $msgType, 1, 1);
                }
            }

            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    public function astroSendUpdate($uid, $astrId, $data)
    {
        try
        {
            $chatId = $this->getIdByAstrIdAndUid($astrId, $uid);
            $info = $chatId > 0 ? $this->getInfoById($chatId) : null;
            if ($info)
            {
                if ($info['consult_num'] > 0)
                {   // 我的 客户
                    $listType = 3;
                } elseif ($info['reply_num'] > 0)
                {   // 沟通中
                    $listType = 2;
                    if (isset($data['consult_num']))
                    {
                        $listType = 3;
                        $rmListType = 2;
                    }
                } else
                {   // 待转化
                    $listType = 1;
                    if (isset($data['consult_num']))
                    {
                        $listType = 3;
                        $rmListType = 1;
                    } elseif (isset($data['reply_num']))
                    {
                        $listType = 2;
                        $rmListType = 1;
                    }
                }

                $this->updateData($info['id'], $astrId, $data, $listType, $rmListType ?? -1);
            }

            return true;
        }
        catch (\Exception $e)
        {
            \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
            return false;
        }
    }

    /**
     * 获取指定用户和占星师ID的  会话ID
     * @param int $astrId
     * @param int $uid
     * @return int
     * @throws \Exception
     */
    public function getIdByAstrIdAndUid(int $astrId, int $uid): int
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('astrid_uid', $astrId . ':' . $uid)
            ->getDataAndSet(function () use ($astrId, $uid)
            {
                try
                {
                    $id = $this->where(['uid' => $uid, 'astr_id' => $astrId])->order('id desc')->value('id');
                    if ($id)
                    {
                        $data = ['id' => $id];
                    } else
                    {
                        $data = ['id' => 0];
                    }
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = ['id' => 0];
                }
                return $data;
            }, [], 'astrid_uid');

        return (int)($data['id'] ?? 0);
    }

    /**
     * @param array $ids
     * @param array|null $type
     * @param string $sortType
     * @return array
     */
    public function getInfoByIdsInData($ids, $type, $sortType)
    {
        if ($ids)
        {   // 获取未删除 的数据
            $where = ['id' => ['in', $ids]];
        } else
        {   // 获取指定pid  未删除 且 未隐藏的数据
            $where = ['id' => $type[0]];
        }
        $field = 'uid,status,last_chat_detail_id,last_chat_detail_time,user_last_msg_time,astr_id,unread_num,question_num,reply_num,delay_num,consult_num,consult_coin,last_consult_time,create_time,update_time';
        try
        {
            $data = $this->field($field)
                ->where($where)
                ->column($field, 'id');
        }
        catch (\Exception $e)
        {
            $data = [];
        }
        return $data;
    }

    public function batchGetInfoByIds($cids, $field = [])
    {
        $resData = parent::batchGetInfoByIds($cids, $field);

        return $this->dataInit($resData);
    }

    /**
     * 数据初始化
     * @param array $data
     * @return array
     */
    public function dataInit(array $data)
    {
        foreach ($data as $index => $itemData)
        {
            $data[$index] = arrayKeyData2int($itemData, ['id', 'astr_id', 'uid', 'status', 'last_chat_detail_id', 'last_chat_detail_time', 'user_last_msg_time', 'unread_num', 'question_num', 'reply_num', 'delay_num', 'consult_num', 'consult_coin', 'last_consult_time', 'create_time', 'update_time']);
        }

        return $data;
    }

    public function pageDataResert(array $data)
    {
        $resData = [];
        $now0Time = strtotime(date('Y-m-d')); // 今日0点时间
        $nowTime = time(); // 当前时间
        $userModel = new User();

        $consultChatRecordDetailsModel = new Zlcr3ConsultChatRecordDetails();
        foreach ($data as $key => $item)
        {
            $userInfo = $userModel->getUserinfo(['id' => $item['uid']]);
            $chatDetail = $consultChatRecordDetailsModel->getInfoById($item['last_chat_detail_id'], ['content', 'data_type', 'extend']);

            switch ($chatDetail['data_type'])
            {
                case 1:
                case 4:
                    $content = $chatDetail['content'];
                    break;
                case 2:
                    $content = '[图片]';
                    break;
                case 3:
                    $content = '[语音连线]';
                    break;
                default:
            }

            $resData[$key] = [
                'uid' => $item['uid'],
                'name' => $userInfo['nickname'],
                'avatar' => $userInfo['avatar'],
                'des' => $content ?? '',
                'des_color' => $item['unread_num'] > 0 ? '#FF5151' : '#9FA1AA',
                'msg_num' => $item['unread_num'],   // 未读数
                'time' => $this->timeConvert($item['last_chat_detail_time'], $now0Time, $nowTime),
            ];
        }

        return $resData;
    }

    /**
     * 时间转换
     * @param int $time 待转换的时间
     * @param int $now0Time 今日零点时间
     * @return string
     */
    public function timeConvert(int $time, int $now0Time, int $nowTime)
    {
        $t = $now0Time - $time;
        if ($t <= 0)
        {
            $t2 = $nowTime - $time;

            if ($t2 < 3600)
            {
                $i = floor($t2 / 60);
                $timeStr = max($i, 1) . '分钟前';
            } elseif ($t2 < 7200)
            {
                $timeStr = '1小时前';
            } else
            {
                $timeStr = date('H:i', $time);
            }
        } elseif ($t <= 86400)
        {
            $timeStr = date('昨日', $time);
        } else
        {
            $timeStr = date('m月d日', $time);
        }

        return $timeStr;
    }

    /**
     * 获取 用户咨询消息未读总数
     * @param int $astrId
     * @param int $dataType 1=>待转化  2=>沟通中  3=>我的客户
     * @return int
     * @throws \Exception
     */
    public function getAstrUnreadAllNum(int $astrId, int $dataType): int
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel)
            ->setCacheKeyDetail('unread_num', $astrId . ':' . $dataType)
            ->getDataAndSet(function () use ($astrId, $dataType)
            {
                try
                {
                    $where = ['astr_id' => $astrId];
                    switch ($dataType)
                    {
                        case 3:
                            $where['consult_num'] = ['>', 0];
                            break;
                        case 2:
                            $where['reply_num'] = ['>', 0];
                            $where['consult_num'] = 0;
                            break;
                        default:
                            $where['reply_num'] = 0;
                            $where['consult_num'] = 0;
                    }
                    $dataList = $this->where($where)->column('unread_num', 'id');
                    $data = [0 => 0];
                    foreach ($dataList as $id => $num)
                    {
                        $data[$id] = $num;
                    }
                    return $data;
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $data = [0 => 0];
                }
                return $data;
            }, [], 'unread_num');

        return (int)array_sum($data);
    }

    /**
     * 更新 用户咨询消息未读总数
     * @param int $astrId
     * @param int $chatId
     * @param int $dataType 1=>待转化  2=>沟通中  3=>我的客户
     * @param int $type 类型 1=>自增未读数 2=>设置未读数
     * @param int $num
     * @return void
     * @throws \Exception
     */
    public function setAstrUnreadAllNumInc(int $astrId, int $chatId, int $dataType, int $type, int $num = 1)
    {
        if ($type === 1)
        {   // 自增未读 消息数量
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('unread_num', $astrId . ':' . $dataType)->setCacheInc($chatId, 'unread_num', $num);
        } else
        {   // 设置 未读消息 数量
            CacheManage::getInstance()->setCacheConfig($this->cacheModel)->setCacheKeyDetail('unread_num', $astrId . ':' . $dataType)->setCache([$chatId => $num], 'unread_num', true);
        }
    }
}